﻿using ClientAppraise.ViewModels.Validator;
using ClientAppraise.Views.Pages.Corpus.CorpusAdornType.Controls;
using ClientAppraise.Views.Pages.Corpus.CorpusType.Controls;
using ClientDao.Corpus;
using ClientInfrastructure.Dto;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ShareCode.Dto;
using ShareCode.Dto.Corpus;
using ShareCode.Entity.Corpus;
using ShareCode.KeyValue.Corpus;
using ShareCode.Util.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ClientAppraise.ViewModels.Pages.Corpus.Corpus.Admin
{
    public partial class NewViewModel(CorpusCorpusDal dal) : MyObservableValidator, IInitDataContextViewModel
    {
        CorpusCorpusDal Dal = dal;

        public long VersionId { get; private set; }
        public long CorpusSenseId { get; private set; }
        public CorpusCorpusWithTypeDto? CorpusWithTypeDto { get; private set; }

        public void InitDataContext(PageParameterDto? dataContext)
        {
            PageTitle = "添加语料";

            if (dataContext != null)
            {
                (VersionId, CorpusSenseId, CorpusWithTypeDto) = ((long, long, CorpusCorpusWithTypeDto))dataContext.Model!;
            }

            if (EnumList == default || EnumList.Count < 1)
            {
                EnumList = EnumHelper.GetAllItems<EnumCorpusContentType>();
            }


        }

        #region
        [ObservableProperty]
        private string? pageTitle;

        [ObservableProperty]
        private List<EnumExtendModel> enumList = [];

        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? title;
        [ObservableProperty]
        private string? remarks;
        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? theCode;
        [ObservableProperty]
        private int contentType;
        [ObservableProperty]
        private bool isKV;
        long corpusTypeId;
        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? corpusTypeTitle;
        private long corpusSenseid;
        private long versionId;
        #endregion

        private CorpusCorpusEntity InitEntity()
        {
            CorpusCorpusEntity entity;
            if (CorpusWithTypeDto is null)
            {
                entity = new CorpusCorpusEntity();
            }
            else
            {
                entity = CorpusWithTypeDto;
            }

            entity.Title = Title;
            entity.Remarks = Remarks;
            entity.TheCode = TheCode;
            entity.CorpusTypeId = corpusTypeId;
            entity.IsKv = IsKV ? 1 : 0;
            entity.ContentType = ContentType;

            //这里正常处理，服务器端会决定如何操作这条记录
            entity.VersionId = VersionId;
            entity.CorpusSenseId = CorpusSenseId;

            return entity;
        }


        [RelayCommand]
        private async Task OnSubmitAsync()
        {
            ValidateAllProperties();

            if (this.HasErrors)
            {
                App.MySnackbar.Danger("没有完成表单填写", "没有完成表单填写");
                return;
            }

            await App.MyContentDialog.ShowRingLoadingAsync(async () =>
            {
                try
                {
                    CorpusCorpusEntity entity = InitEntity();


                    if (entity.Id == 0)
                    {
                        ResultDto<long> reslut = await Dal.InsertAsync(entity);
                        if (reslut.Success)
                        {
                            App.MySnackbar.Success("成功添加：" + entity.Title);
                            App.MyNavigation.GoBack();
                            return;
                        }

                        //显示错误信息
                        ValidateAllPropertiesWithServer(reslut?.DetailMSg ?? []);

                        if (!string.IsNullOrEmpty(reslut?.Message))
                        {
                            App.MySnackbar.Danger("添加失败:", reslut.Message);
                        }
                    }
                    else
                    {
                        ResultDto<bool> reslut = await Dal.UpdateAsync(entity);
                        if (reslut.Success)
                        {
                            App.MySnackbar.Success("成功修改：" + entity.Title);
                            App.MyNavigation.GoBack();//这里先不考虑性能问题，服务器端可以返回操作的记录，然后客户端再次合并，这里就要缓存数据了
                            return;
                        }

                        //显示错误信息
                        ValidateAllPropertiesWithServer(reslut?.DetailMSg ?? []);

                        if (!string.IsNullOrEmpty(reslut?.Message))
                        {
                            App.MySnackbar.Danger("修改失败:", reslut.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    App.MySnackbar.Danger(ex.Message, ex.Message);
                }
                finally
                {
                    App.MyContentDialog.CloseLoading();
                }
            });
        }

        public async Task ShowDrawerAsync()
        {
            if (!App.Current.Dispatcher.CheckAccess())
            {
                await Application.Current.Dispatcher.Invoke(async () => await ShowDrawerAsync());
                return;
            }

            var drawerReturn = await App.MyDrawer.ShowDrawer<UcCorpusTypeSelector>(obj =>
            {
                if (obj is IInitDataContextViewModel model)
                {
                    model.InitDataContext(new PageParameterDto { Model = new List<long> { corpusTypeId } });
                }
            });

            if (drawerReturn.Data is List<CorpusTypeEntity> selected)
            {
                corpusTypeId = selected.Select(x => x.Id).FirstOrDefault();
                CorpusTypeTitle = selected.Select(y => y.Title).FirstOrDefault();

            }
            else
            {
                corpusTypeId = 0;
                CorpusTypeTitle = "";
            }

        }
    }
}
